package com.feicheng.iou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feicheng.iou.bean.InformationBean;
import com.feicheng.iou.constant.ProvideConstant;
import com.feicheng.iou.constant.RepaymentConstant;
import com.feicheng.iou.constant.SessionConstant;
import com.feicheng.iou.constant.StatusCodeConstant;
import com.feicheng.iou.entity.Payment;
import com.feicheng.iou.entity.PaymentItem;
import com.feicheng.iou.entity.PaymentOptions;
import com.feicheng.iou.exception.SystemExceptionV110;
import com.feicheng.iou.mapper.PaymentItemMapper;
import com.feicheng.iou.mapper.PaymentMapper;
import com.feicheng.iou.mapper.PaymentOptionsMapper;
import com.feicheng.iou.pojo.PaymentPOJO;
import com.feicheng.iou.pojo.ResultBaomingPOJO;
import com.feicheng.iou.pojo.ResultPaymentPOJO;
import com.feicheng.iou.pojo.login.LoginReturnPOJO;
import com.feicheng.iou.result.ResultInfo;
import com.feicheng.iou.result.ResultInfoV110;
import com.feicheng.iou.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feicheng.iou.util.PageUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
//import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tianchunlei
 * @since 2021-06-28
 */
@Service
@Slf4j
@Setter
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private PaymentItemMapper paymentItemMapper;
    @Autowired
    private PaymentOptionsMapper paymentOptionsMapper;

    @Override
    public ResultInfoV110 listAll(PaymentPOJO paymentPOJO) {
        log.info("PaymentServiceImpl类listAll进入,参数为: " + paymentPOJO);

        //定义一个放返回数据的Map
        HashMap<Object, Object> resultMap = new HashMap<>();
        //获取传入数据中的pege当前页，size每页条数得出当前页起始数据索引
        Integer pageIndex = PageUtil.getPageIndex(paymentPOJO.getPage(), paymentPOJO.getSize());
        //把数据索引封装到paymentPOJO
        paymentPOJO.setPageIndex(pageIndex);
        //调用Mapper中查询条数的方法得出条数封装进paymentPOJO
        paymentPOJO.setTotal(paymentMapper.queryPaymentAllCount(paymentPOJO));
        //根据传入的pojo查询，结果封装到resultPaymentPOJOSList
        List<ResultPaymentPOJO> resultPaymentPOJOList = paymentMapper.queryPaymentAll(paymentPOJO);
        //获取pageutil里的pageinfo里的数据封装到pageinfo这个map
        Map<String, Integer> pageInfo = PageUtil.getPageInfo(paymentPOJO.getPage(), paymentPOJO.getSize(), paymentPOJO.getTotal());

        //把pageinnfo这个map封装到resultMap中
        resultMap.put("pageInfo", pageInfo);
        //把resourcePOJOSList这个list封装到resultMap中
        resultMap.put("list", resultPaymentPOJOList);

        resultPaymentPOJOList.forEach(System.out::println);

        log.info("PaymentServiceImpl类listAll结束");

        return ResultInfoV110.success(resultMap);
    }

    @Override
    public ResultInfoV110 statistics() {
        log.info("PaymentServiceImpl类statistics结束");

        Map resultMap = new HashMap<>();
        /* 查询状态为待确认的支付数据条数 */
        QueryWrapper<Payment> daiqueren = new QueryWrapper<>();
        daiqueren.eq("status", ProvideConstant.DAIQUEREN);
        Integer daiquerenNum = paymentMapper.selectCount(daiqueren);

        /* 查询状态为还款中的支付数据条数 */
        QueryWrapper<Payment> huankuanzhong = new QueryWrapper<>();
        huankuanzhong.eq("status", ProvideConstant.HUANKUANZHONG);
        Integer huankuanzhongNum = paymentMapper.selectCount(huankuanzhong);

        /* 查询状态为已生效的支付数据条数 */
        QueryWrapper<Payment> yishengixao = new QueryWrapper<>();
        yishengixao.eq("status", ProvideConstant.YISHENGXIAO);
        Integer yishengixaoNum = paymentMapper.selectCount(yishengixao);

        /* 查询状态为已取消的支付数据条数 */
        QueryWrapper<Payment> yiquxiao = new QueryWrapper<>();
        yiquxiao.eq("status", ProvideConstant.YIQUXIAO);
        Integer yiquxiaoNum = paymentMapper.selectCount(yiquxiao);

        /* 查询状态为已结清的支付数据条数 */
        QueryWrapper<Payment> yijieqing = new QueryWrapper<>();
        yijieqing.eq("status", ProvideConstant.YIJIEQING);
        Integer yijieqingNum = paymentMapper.selectCount(yijieqing);

        /* 查询状态为未通过的支付数据条数 */
        QueryWrapper<Payment> weitongguo = new QueryWrapper<>();
        weitongguo.eq("status", ProvideConstant.WEITONGUO);
        Integer weitongguoNum = paymentMapper.selectCount(weitongguo);

        //查询结果数据封装放入map
        resultMap.put("DAIQUEREN", daiquerenNum);
        resultMap.put("HUANKUANZHONG", huankuanzhongNum);
        resultMap.put("YISHENGXIAO", yishengixaoNum);
        resultMap.put("YIQUXIAO", yiquxiaoNum);
        resultMap.put("YIJIEQING", yijieqingNum);
        resultMap.put("WEITONGUO", weitongguoNum);

        log.info("PaymentServiceImpl类statistics结束");
        log.debug("PaymentServiceImpl类statistics方法饭绘的map是" + resultMap);
        return ResultInfoV110.success(resultMap);
    }

    @Override
    public ResultInfoV110 operationPass(Integer paymentId, HttpServletRequest request) {
        log.info("PaymentServiceImpl类operationPass方法进入");

        //取到当前登录用户session中的userid
        LoginReturnPOJO attribute = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        Integer userId = attribute.getUser().getUserId();
        LocalDate now = LocalDate.now();

        /* 把传入的ID放去对象中，并写入修改的状态值，抵用mapper实现修改操作 */
        LocalDate requestDate = paymentMapper.selectById(paymentId).getRequestDate();
        Integer poid = paymentMapper.selectById(paymentId).getPoid();
        Payment payment = new Payment();
        payment.setId(paymentId)
                .setStatus(ProvideConstant.YISHENGXIAO)
                .setUu(userId);
        if (now.isBefore(requestDate)) {
            payment.setAllowDate(now).
                    setRunDate(requestDate);
        } else {
            payment.setAllowDate(now)
                    .setRunDate(now);

        }


        int updateStatusById = paymentMapper.updateById(payment);
        //验证修状态信息是否成功
        if (updateStatusById == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改状态信息"));
        }

        QueryWrapper<PaymentItem> paymentItemQueryWrapper = new QueryWrapper<>();
        paymentItemQueryWrapper.eq("p_id", paymentId);
        List<PaymentItem> payments = paymentItemMapper.selectList(paymentItemQueryWrapper);
        Integer i = 0;
        PaymentOptions paymentOptions = paymentOptionsMapper.selectById(poid);
        for (PaymentItem paymentItem : payments) {
            Integer paymentItemId = paymentItem.getId();
            UpdateWrapper<PaymentItem> paymentItemUpdateWrapper = new UpdateWrapper<>();
            LocalDate localDate = payment.getRunDate().withDayOfMonth(Integer.valueOf(paymentOptions.getPayDate())).plusMonths(i + 1);
            LocalDateTime localDateTime = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toLocalDateTime();
            paymentItemUpdateWrapper.eq("id", paymentItemId).set("status", RepaymentConstant.DAIHUANKUAN).set("plan_pay_date", localDateTime);
            paymentItemMapper.update(null, paymentItemUpdateWrapper);
            i++;
        }

//        /* 把传入的paymentId装入条件构造器，分期列表状态改为待还款，调用mapper进行修改操作 */
//        UpdateWrapper<PaymentItem> paymentItemUpdateWrapper = new UpdateWrapper<>();
//        paymentItemUpdateWrapper.eq("p_id",paymentId).set("status",RepaymentConstant.DAIHUANKUAN);
//        paymentItemMapper.update(null,paymentItemUpdateWrapper);

        log.info("PaymentServiceImpl类operationPass方法结束");
        return ResultInfoV110.success();
    }

    @Override
    public ResultInfoV110 operationNoPass(Integer paymentId, HttpServletRequest request) {
        log.info("PaymentServiceImpl类operationPass方法进入");

        //取到当前登录用户session中的userid
        LoginReturnPOJO attribute = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        Integer userId = attribute.getUser().getUserId();

        /* 把传入的ID放去对象中，并写入修改的状态值，抵用mapper实现修改操作 */
        Payment payment = new Payment();
        payment.setId(paymentId);
        payment.setUu(userId);
        payment.setStatus(ProvideConstant.WEITONGUO);
        int updateStatusById = paymentMapper.updateById(payment);
        //验证修状态信息是否成功
        if (updateStatusById == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改状态信息"));
        }

        log.info("PaymentServiceImpl类operationPass方法结束");
        return ResultInfoV110.success();
    }

    @Override
    public ResultInfoV110 operationhalt(Integer paymentId, HttpServletRequest request) {
        log.info("PaymentServiceImpl类operationPass方法进入");

        //取到当前登录用户session中的userid
        LoginReturnPOJO attribute = (LoginReturnPOJO) request.getSession().getAttribute(SessionConstant.CURRENT);
        Integer userId = attribute.getUser().getUserId();

        /* 把传入的ID放去对象中，并写入修改的状态值，抵用mapper实现修改操作 */
        Payment payment = new Payment();
        payment.setId(paymentId);
        payment.setUu(userId);
        payment.setStatus(ProvideConstant.YIQUXIAO);
        int updateStatusById = paymentMapper.updateById(payment);
        //验证修状态信息是否成功
        if (updateStatusById == 0) {
            throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001, "更改状态信息"));
        }

        log.info("PaymentServiceImpl类operationPass方法结束");
        return ResultInfoV110.success();
    }

}
